package cn.jietuo.juc.c_008_interview1;


import java.util.ArrayList;
import java.util.List;

/**
 * @author zhangx & jietuo_zx@163.com
 * @version 1.0
 * @date 2020/5/8
 * @description: 实现一个容器，提供两个方法，add,size
 * 写两个线程，线程1添加10个元素到容器中，线程2实现监控元素的个数，
 * 当个数为5时，线程2给出提示并退出，
 */
public class T02 {

    private List<Integer> list = new ArrayList<>();

    private void add(Integer i) {
        list.add(i);
    }

    private Integer size() {
        return list.size();
    }

    public static void main(String[] args) {
        T02 t = new T02();
        Object lock = new Object();

        new Thread(() -> {
            synchronized (lock) {
                for (int i = 0; i < 10; i++) {
                    t.add(i);
                    System.out.println("add:" + i);
                    if (i == 4) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }).start();

        new Thread(() -> {
            while (true) {
                synchronized (lock) {
                    if (t.size() == 5) {
                        lock.notify();
                        break;
                    }
                }
            }
            System.out.println("数量添加到5，退出");
        }).start();
    }
}
